#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <string>
#include <time.h>
using namespace std;
#define Multi_thread_NUM 5
//pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
int tickets = 1000;


class Thread_Data
{
public:
    Thread_Data(pthread_mutex_t* mtx, size_t  num)
    :_mtx(mtx)
    ,_number_of_thread(num)
    {}
public:
    pthread_mutex_t* _mtx;
    size_t _number_of_thread;
};

void *GetTickets(void * args)
{
    
    Thread_Data* TD = (Thread_Data*)args;
    while(1)
    {
        pthread_mutex_lock(TD->_mtx);
        if(tickets > 0)
        {
            usleep(rand() % 1500);
            tickets--;
            pthread_mutex_unlock(TD->_mtx);
            cout<<TD->_number_of_thread<<": 还剩下"<<tickets<<"张票"<<endl;
        }
        else
        {
            pthread_mutex_unlock(TD->_mtx);
            break;
        }
    }

    //sleep(rand() % 50);
    return nullptr;
}



int main()
{
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx,nullptr);
    srand((unsigned long)time(nullptr) ^ getpid() ^ 0x147);
    
    //1、首先创建多线程
    
    pthread_t tid[Multi_thread_NUM];
    Thread_Data *td[Multi_thread_NUM];
    for(size_t i = 0;i<Multi_thread_NUM;i++)
    {
        td[i] = new Thread_Data(&mtx,i);
        int tem = 1;
        tem = pthread_create(tid+i,nullptr,GetTickets,(void*)td[i]);
        if(tem == 0) cout<<"创建线程成功"<<endl;
    }
    //回收多线程
    for(auto e:tid)
    {
        pthread_join(e,nullptr);
    }
    //回收堆空间
    for(auto e:td)
    {
        free(e);
    }
    //回收锁
    pthread_mutex_destroy(&mtx);

    return 0;
}